using UnityEngine;
using System.Collections;

public class playerScript : MonoBehaviour 
{

    public int health = 100, jumpSpeed = 20, gravity = 80, stemina = 100, speed = 20, crouchSpeed = 10, sprint = 30;

    private Vector3 moveDirection = Vector3.zero;
    private bool grounded = false, crouched = false, recovering = false;

    private void Start()
    {
        //if (!networkView.isMine)
        //{
        //    this.enabled = false;
        //}
    }


    private void Update()
    {
        if (grounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            if (Input.GetKey(KeyCode.LeftShift))
                moveDirection *= sprint;
            else if (crouched)
                moveDirection *= crouchSpeed;
            else
                moveDirection *= speed;
            moveDirection = transform.TransformDirection(moveDirection);


            if (Input.GetKeyDown(KeyCode.Space))
            {
                moveDirection.y += jumpSpeed;
            }
        }
        
        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            
        }

        moveDirection.y -= gravity * Time.deltaTime;
        grounded = (GetComponent<CharacterController>().Move(moveDirection * Time.deltaTime) & CollisionFlags.CollidedBelow) != 0;
    }


    [RPC]
    public void LowerHealth(int newHealth)
    {
        recovering = false;
        health = newHealth;
        Invoke("restoreHealth", 5);
    }

    private void restoreHealth()
    {
        StartCoroutine(recover());
        recovering = true;
    }

    private IEnumerator recover()
    {
        if (recovering)
        {
            if (health >= 100)
            {
                health = 100;
            }
            else
            {
                health++;
                yield return new WaitForSeconds(0.3f);
                StartCoroutine(recover());
            }
        }
    }
}
